<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\GoodCate;

class GoodCateController extends BaseController {
  public function actionAllList(){
    $first_list = GoodCate::find()->where(['parent_id' => 0, 'status' => 1])->orderBy('sort desc, created_at desc')->all();
    $data = [];
    if ($first_list) {
      foreach($first_list as $v) {
        $second_list = GoodCate::find()->where(['parent_id' => $v->id, 'status' => 1])->orderBy('sort desc, created_at desc')->all();
        $second_data = [];
        if ($second_list) {
          foreach($second_list as $vv) {
            $second_data[] = [
              'id' => $vv->id,
              'name' => $vv->name,
              'sub_name' => $vv->sub_name,
              'bg_cover' => $vv->bg_cover,
              'icon' => $vv->icon
            ];
          }
          $data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'sub_name' => $v->sub_name,
            'bg_cover' => $v->bg_cover,
            'icon' => $v->icon,
            'children' => $second_data
          ];
        } 
      }
    }
    return Re::data(['data' => $data]);
  }

  public function actionFirstList(){
    $list = GoodCate::find()->where(['parent_id' => 0, 'status' => 1])->orderBy('sort desc, created_at desc')->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'name' => $v->name,
          'sub_name' => $v->sub_name,
          'bg_cover' => $v->bg_cover,
          'icon' => $v->icon
        ];
      }
    }
    return Re::data(['data' => $data]);
  }

  public function actionSecondList(){
    $parent_id = Yii::$app->request->post('parent_id', 0);
    $parent_cate = GoodCate::findOne($parent_id);
    if (empty($parent_cate)) {
      return Re::data(null, '一级分类读取失败', Re::ERROR);
    }
    $list = GoodCate::find()->where(['parent_id' => $parent_id, 'status' => 1])->orderBy('sort desc, created_at desc')->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'name' => $v->name,
          'sub_name' => $v->sub_name,
          'bg_cover' => $v->bg_cover,
          'icon' => $v->icon
        ];
      }
    }
    return Re::data(['data' => $data]);
  }
}
